package com.alinesno.cloud.base.notice.enable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;

/**
 * 自动引入dubbo服务实现
 * 
 * @author WeiXiaoJin
 * @sine 2019年4月5日 下午3:34:07
 */
public class NoticeConfigurationSelector
		implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {

	private static final Logger log = LoggerFactory.getLogger(NoticeConfigurationSelector.class);

	private ResourceLoader resourceLoader;
	private Environment environment;

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		// 获取Class的扫描器
		ClassPathScanningCandidateComponentProvider scanner = getScanner();
		scanner.setResourceLoader(this.resourceLoader);

		// 指定扫描的基础包
		String basePackage = ClassUtils.getPackageName(importingClassMetadata.getClassName());
		log.debug("basc package:{}" , basePackage);
	}
	
	/**
	 * 构造Class扫描器
	 */
	protected ClassPathScanningCandidateComponentProvider getScanner() {
		return new ClassPathScanningCandidateComponentProvider(false, this.environment) {
			@Override
			protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
				if (beanDefinition.getMetadata().isInterface()) {
					return !beanDefinition.getMetadata().isAnnotation();
				}
				return false;
			}
		};
	}

}
